import { createSlice, createAsyncThunk, type PayloadAction } from "@reduxjs/toolkit"

interface CounterState {
  value: number
}

const initialState: CounterState = {
  value: 0
}

export const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    increment: state => {
      state.value += 1
    },
    decrement: state => {
      state.value -= 1
    },
    incrementByAmount: (state, action: PayloadAction<number>) => {
      state.value += action.payload
    }
  },
  extraReducers(builder) {
    builder.addCase(asyncFetchCount.pending, () => {
      console.log('pending')
    })
    builder.addCase(asyncFetchCount.fulfilled, (state, action) => {
      state.value += action.payload
    })
    builder.addCase(asyncFetchCount.rejected, (state) => {
      state.value = 0
    })
  },
})

export const asyncFetchCount = createAsyncThunk(
  'counter/fetchCount',
  async (amount: number) => {
    await new Promise(resolve => setTimeout(resolve, 1000))
    return amount
  }
)

export const { increment, decrement, incrementByAmount } = counterSlice.actions
export default counterSlice.reducer